/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */
export default function access(initialState) {
  const { currentUser } = initialState || {};
  return {
    // 是否为主机（主租户）
    isHost(route) {

      if (!currentUser) {
        return false;
      }
      if (route.key) {
        return true;
      }
      const { userAuthority, userName } = currentUser;
      // all route
      const routePaths = userAuthority.routePaths;
      if (userName === 'root') {
        return true;
      }
      if (!routePaths) {
        return false;
      }
      return routePaths.includes(route.path);
    },
    // 是否为开发者
    isRoot() {
      if (!currentUser) {
        return false;
      }
      const { userName } = currentUser;
      return userName === 'root';
    },
    // 是否拥有菜单显示权限
    canAdmin(route) {
      if (!currentUser) {
        return false;
      }
      if (route.key) {
        return true;
      }
      const { userAuthority, userName } = currentUser;
      // all route
      const routePaths = userAuthority.routePaths;

      if (userName === 'root') {
        return true;
      }
      if (!routePaths) {
        return false;
      }
      // 如果是子页面，不判断
      if (route.hideInMenu) {
        return true;
      }
      return routePaths.includes(route.path);
    },
    // 是否拥有按钮操作权限
    canOperation(code) {
      if (!currentUser) {
        return false;
      }
      const { userAuthority, userName } = currentUser;
      // all route
      const operationCodes = userAuthority.operationCodes;
      // all route
      if (userName === 'root') {
        return true;
      }
      return operationCodes.findIndex((c) => c === code) !== -1;
    },
    //  是否显示操作列
    canShowOption(args) {
      // 如果参数不是数组
      if (!(args instanceof Array)) {
        return false;
      }
      if (!currentUser) {
        return false;
      }
      const { userAuthority, userName } = currentUser;
      // all route
      const operationCodes = userAuthority.operationCodes;
      if (userName === 'root') {
        return true;
      }
      let flag = false;
      for (let i = 0; i < args.length; i += 1) {
        const code = args[i];
        if (operationCodes.findIndex((c) => c === code) !== -1) {
          flag = true;
          break;
        }
      }
      return flag;
    },
    //  是否显示更多操作列
    canShowMoreOption(args) {
      // 如果参数不是数组
      if (!(args instanceof Array)) {
        return false;
      }
      if (!currentUser) {
        return false;
      }
      const { userAuthority, userName } = currentUser;
      // all route
      const operationCodes = userAuthority.operationCodes;
      if (userName === 'root') {
        return true;
      }
      let flag = false;
      for (let i = 0; i < args.length; i += 1) {
        const code = args[i];
        if (operationCodes.findIndex((c) => c === code) !== -1) {
          flag = true;
          break;
        }
      }
      return flag;
    },
  };
}
